package com.cby.library.widget.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述信息
 *
 * @author 徐智伟
 * @create 2018/10/23
 */

public abstract class SimpleBaseAdapter<T> extends BaseAdapter {

  protected LayoutInflater mInflater;
  protected Context mContext;
  protected List<T> data;

  public SimpleBaseAdapter(Context context) {
    mInflater = LayoutInflater.from(context);
    this.mContext = context;
    this.data = new ArrayList<>();
  }

  public SimpleBaseAdapter(Context context, List<T> data) {
    mInflater = LayoutInflater.from(context);
    this.mContext = context;
    this.data = data == null ? new ArrayList<T>() :new ArrayList<T>(data);
  }

  @Override
  public int getCount() {
    return data.size();
  }

  @Override
  public T getItem(int position) {
    if (position >= data.size()){
      return null;
    }
    return data.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  /**
   * 获取item的布局resource
   * @return
   */
  public abstract int getItemResource();


  public abstract View getItemView(int position, View convertView, ViewGroup parent,ViewHolder holder);

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (null == convertView){
      convertView = mInflater.inflate(getItemResource(),null);
      holder = new ViewHolder(convertView);
      convertView.setTag(holder);
    }else{
      holder = (ViewHolder)convertView.getTag();
    }
    return getItemView(position,convertView,parent,holder);
  }



  public void addAll(List<T> elems){
    data.addAll(elems);
    notifyDataSetChanged();
  }

  public void add(T elem){
    data.add(elem);
    notifyDataSetChanged();
  }

  public void remove(T elem){
    data.remove(elem);
    notifyDataSetChanged();
  }

  public void reset(){
    data.clear();
    notifyDataSetChanged();
  }

  public void remove(int index){
    data.remove(index);
    notifyDataSetChanged();
  }

  public void replaceAll(List<T> elems){
    data.clear();
    if (elems != null){
      data.addAll(elems);
    }
    notifyDataSetChanged();
  }


  public class ViewHolder{
    private SparseArray<View> views =new SparseArray<View>();

    private View convertView;

    public ViewHolder(View convertView){
      this.convertView = convertView;
    }

    public <T extends View> T findView(int resId){
      View v = views.get(resId);
      if (null == v){
        v = convertView.findViewById(resId);
        views.put(resId,v);
      }
      return (T)v;
    }

    public TextView setTextView(int resId, String text) {
      TextView textView = findView(resId);
      textView.setText(text);
      return textView;
    }
  }
}

